package com.loyal.loyalerp.phone.controller;

import static org.junit.Assert.assertFalse;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpSession;

import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.loyal.loyalerp.commons.ServerResponse;
import com.loyal.loyalerp.humenresource.askleave.model.AskLeave;
import com.loyal.loyalerp.humenresource.askleave.service.AskLeaveService;
import com.loyal.loyalerp.humenresource.categoryDetail.service.CategoryDetailReadService;
import com.loyal.loyalerp.humenresource.user.service.GyUserService;
import com.loyal.loyalerp.model.GyUser;
import com.loyal.loyalerp.phone.util.RequestUtils;
import com.loyal.loyalerp.service.EmployeeService;
import com.loyal.loyalerp.utils.PropertiesUtil;
import com.loyal.loyalerp.utils.ValidateUtil;
import com.loyal.loyalerp.utils.WeixinUtil;

@Controller
@RequestMapping("phone")
public class PhoneController {

	@Autowired
	GyUserService userService;
	@Autowired
	private AskLeaveService askLeaveService;
	@Autowired
	private EmployeeService employeeService;
	@Autowired
	private CategoryDetailReadService detailReadService;

	@RequestMapping("qingJiaInfo")
	public String qingJiaInfo(Integer qingjiaId, HttpServletRequest request) {
		AskLeave askLeave = askLeaveService.askLeaveService(qingjiaId);
		if (askLeave != null) {
			GyUser user = userService.selectUserById(askLeave.getPersonId());
			if (user != null)
				request.setAttribute("username", user.getUsername());
		}
		request.setAttribute("ConfigType", detailReadService.retrieveCategoryDetail(1027));
		request.setAttribute("askLeave", askLeave);
		return "phone/qingJiaInfo";
	}

	@RequestMapping("enterQingJiaPage1")
	public String enterQingJiaPage() {
		return "phone/qingjia";
	}

	// 查看详细请假信息
	@RequestMapping("viewDetail")
	public String enterDetail(String id, Map<String, Object> map) {
		AskLeave list = askLeaveService.selectAskByPrimaryKey(Integer.parseInt(id));
		map.put("info", list);
		return "qingjiq/detail";
	}

	@RequestMapping("enterQingJiaPage")
	public String enterQingJiaPage1() {
		return "qingjiq/qingjia2";
	}

	@RequestMapping("test")
	public String test() {
		return "qingjiq/test";
	}

	@RequestMapping("test2")
	public String test2() {
		return "qingjiq/test2";
	}

	// 验证当前用户身份
	@RequestMapping("valiteCurrentUser")
	public String valiteCurrentUser(HttpServletRequest request,
			@RequestParam(name = "condition", required = false) String condition) {
		String weixinUrl = PropertiesUtil.getValue("weixinUrl");
		if (weixinUrl != null) {
			if (condition == null) {
				return WeixinUtil.getCodeAndRedirect(request, weixinUrl + "/phone/enterQinJia");
			} else {
				return WeixinUtil.getCodeAndRedirect(request, weixinUrl + "/phone/enterCurrentUser");
			}
		}

		else
			return "phone/error";
	}

	@RequestMapping("phoneCheck")
	public String phoneCheck(HttpServletRequest request) {
		String weixinUrl = PropertiesUtil.getValue("weixinUrl");
		if (weixinUrl != null)
			return WeixinUtil.getCodeAndRedirect(request, weixinUrl + "/phone/goCheckPage");
		else
			return "phone/error";
	}

	@RequestMapping("error")
	public String errorPage() {
		return "error";
	}

	@RequestMapping("goCheckPage")
	public String goCheckPage(HttpServletRequest request, String code) {
		HttpSession session = request.getSession();
		String userJsonInfo = WeixinUtil.getUserJsonInfo(session, code);
		if (null == userJsonInfo)
			return "phone/error";
		// String username = RequestUtils.getFieldFromJsonText(userJsonInfo, "name");
		String mobile = RequestUtils.getFieldFromJsonText(userJsonInfo, "mobile");
		GyUser user = loginByMobile(mobile);
		if (null == user)
			return "phone/error";
		if (!ValidateUtil.validateCheck("rs_qingjiaapply")) {
			return "basedata/askleave/403";
		}
		request.setAttribute("User", employeeService.getAllEmploy());
		return "phone/checkPage";
	}

	@RequestMapping("redirectCheckPage")
	public String redirectCheckPage(HttpServletRequest request) {
		request.setAttribute("User", employeeService.getAllEmploy());
		return "phone/checkPage";
	}

	@RequestMapping("testQingJia")
	public String testQingJia(HttpServletRequest request, Map<String, Object> map) {
		HttpSession session = request.getSession();
		String mobile = "13602520960";
		GyUser user = loginByMobile(mobile);
		if (null == user)
			return "phone/error";
		// int id = userService.selectUserIdByUserName(username);
		map.put("id", user.getId());
		map.put("username", user.getUsername());
		session.setAttribute("mobile", mobile);
		return "qingjiq/qingjia2";
	}

	@RequestMapping("enterQinJia")
	public String enterQinJia(HttpServletRequest request, String code, Map<String, Object> map) {
		HttpSession session = request.getSession();
		String userJsonInfo = WeixinUtil.getUserJsonInfo(session, code);
		if (null == userJsonInfo)
			return "phone/error";
		// String wxusername = RequestUtils.getFieldFromJsonText(userJsonInfo, "name");
		String mobile = RequestUtils.getFieldFromJsonText(userJsonInfo, "mobile");
		GyUser user = loginByMobile(mobile);
		if (null == user)
			return "phone/error";
		// int id = userService.selectUserIdByUserName(username);
		map.put("id", user.getId());
		map.put("username", user.getUsername());
		session.setAttribute("mobile", RequestUtils.getFieldFromJsonText(userJsonInfo, "mobile"));
		return "qingjiq/qingjia2";
	}

	@RequestMapping("enterCurrentUser")
	public String enterCurrentUser(HttpServletRequest request, String code, Map<String, Object> map) {
		HttpSession session = request.getSession();
		String userJsonInfo = WeixinUtil.getUserJsonInfo(session, code);
		if (null == userJsonInfo)
			return "phone/error";
		// String wxusername = RequestUtils.getFieldFromJsonText(userJsonInfo, "name");
		String mobile = RequestUtils.getFieldFromJsonText(userJsonInfo, "mobile");
		GyUser user = loginByMobile(mobile);
		if (null == user)
			return "phone/error";
		// int id = userService.selectUserIdByUserName(username);
		map.put("id", user.getId());
		map.put("username", user.getUsername());
		List<AskLeave> list = askLeaveService.selectPersonQinJiaByPhone(mobile);
		map.put("list", list);
		session.setAttribute("mobile", RequestUtils.getFieldFromJsonText(userJsonInfo, "mobile"));
		return "qingjiq/getUserQinJia";
	}

	// private void loginByUsername(String username) {
	// GyUser user = userService.selectUserByUserName(username);
	// if (user != null) {
	// login(user.getUsercode(), user.getPassword());
	// SecurityUtils.getSubject().getSession().setAttribute("user", user);
	// }
	// }

	private GyUser loginByMobile(String mobile) {
		try {
			List<GyUser> users = employeeService.getUserByMobile(mobile);
			if (users == null || users.size() != 1)
				return null;
			GyUser user = users.get(0);

			login(user.getUsercode(), user.getPassword());
			SecurityUtils.getSubject().getSession().setAttribute("user", user);

			return user;
		} catch (Exception ex) {
			return null;
		}
	}

	private boolean login(String id, String password) {
		Subject currentUser = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(id, password);
		try {
			currentUser.login(token);
			return true;
		} catch (UnknownAccountException e) {
			e.printStackTrace();
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (AuthenticationException e) {
			e.printStackTrace();
		}
		return false;
	}

	@ResponseBody
	@RequestMapping("/weixinAdd") // 增删改
	public Object weixinAdd(HttpServletRequest request, @RequestBody AskLeave askLeave) {
		if (askLeave.getStartTime() == null) {
			return ServerResponse.createByError("参数错误：开始时间");
		}
		if (askLeave.getEndTime() == null) {
			return ServerResponse.createByError("参数错误：截止时间");
		}
		if (askLeave.getDays() == null) {
			return ServerResponse.createByError("参数错误：请假天数");
		}

		if (!askLeave.getStartTime().before(askLeave.getEndTime())) {
			return ServerResponse.createByError("开始时间不能晚于截止时间");
		}
		if (askLeave.getStartTime().getMonth() != askLeave.getEndTime().getMonth()) {
			return ServerResponse.createByError("因考勤按月统计，因此请假时间如果跨月，请分开申请");
		}

		if (ValidateUtil.validateUser() == null) {
			ServerResponse.createByError("当前用户没有认证授权！");
		} else if (askLeaveService.kaoQinMonthHasExist(askLeave.getStartTime().getYear() + 1900,
				askLeave.getStartTime().getMonth() + 1, ValidateUtil.validateUser().getId())) {
			return ServerResponse.createByError("请假的起始日期已经进行了月结结算");
		}
		if (askLeave.getDays().compareTo(
				new BigDecimal(askLeave.getEndTime().getDate() - askLeave.getStartTime().getDate() + 1)) > 0) {
			return ServerResponse.createByError("请假天数明显太长");
		}

		askLeave.getStartTime().setSeconds(0);
		askLeave.getEndTime().setSeconds(0);

		askLeave.setKjYear(askLeave.getStartTime().getYear() + 1900);
		askLeave.setPeriod(askLeave.getStartTime().getMonth() + 1);
		askLeave.setCheckerId(0);
		if (askLeaveService.addAskLeave(askLeave)) {
			return ServerResponse.createBySuccess("请假申请提交成功");
		}
		return ServerResponse.createByError("请假申请提交失败");
	}

	// 文件选择后就上传。“提交”时候只需要保存文件名称即可。
	// 为了防止上传文件失败，前端需要记录每个文件是否上传成功
	@ResponseBody
	@RequestMapping("/weixinFilesUpload") // 文件名称由前段决定， USERID + YYYYMMDDHHMMSS + 三位随机数
	public Object weixinFilesUpload(HttpServletRequest request, String guid,
			@RequestParam(value = "file", required = true) MultipartFile file) {

		ServerResponse.createByError("当前用户没有认证授权！");

		String path = "";
		if (file != null && !file.isEmpty()) {
			// SCLD
			if (!file.getContentType().contains("image")) {
				return ServerResponse.createByError("请选择正确的图片");
			}
			String pathRoot = PropertiesUtil.getValue("urlRoot");
			pathRoot = request.getSession().getServletContext().getRealPath(pathRoot);
			path = guid + "-" + file.getOriginalFilename();
			try {

				file.transferTo(new File(pathRoot + path));
			} catch (IllegalStateException e) {
				e.printStackTrace();
				return ServerResponse.createByError(e.getMessage());
			} catch (IOException e) {
				e.printStackTrace();
				return ServerResponse.createByError(e.getMessage());
			}
		}

		return ServerResponse.createBySuccess(path);
	}

	@ResponseBody
	@RequestMapping("/weixinFilesDelete") // 此处上传的文件名字为上面回传的。
	public Object weixinFilesDelete(HttpServletRequest request, String fileName) {

		System.out.println(fileName);

		if (ValidateUtil.validateUser() == null) {
			ServerResponse.createByError("当前用户没有认证授权！");
		}

		if (fileName != null && !fileName.isEmpty()) {
			try {
				String pathRoot = PropertiesUtil.getValue("pathRoot");

				File file = new File(pathRoot + "/" + fileName);
				// 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
				if (file.exists() && file.isFile()) {

					file.delete();
				}
			} catch (Exception e) {
				e.printStackTrace();
				return ServerResponse.createByError(e.getMessage());
			}
		}

		return ServerResponse.createBySuccess("OK");
	}

}
